<?php

class ItemMapper
{
	private function __construct() {}
	private function __destruct() {}
	private function __clone() {}
	
	public static function insert(ItemObject $item)
	{
		$query = sprintf("INSERT INTO `items` (`name`, `make_points`, `type`, `desc`) VALUES ('%s', %f, %d, '%s');",
				DataBase::i()->escape($item->name()), $item->makePoints(),
				$item->type(), DataBase::i()->escape($item->desc()));
		$res = DataBase::i()->query($query);
		if ($res === false)
			return false;
	
		$item->setId(DataBase::i()->insertId());
	
		return true;
	}

	public static function update(ItemObject $item)
	{
		$query = sprintf("UPDATE `items` SET `name` = '%s', `make_points` = %f, `type` = %d, `desc` = '%s' WHERE `id` = %d",
				DataBase::i()->escape($item->name()), $item->makePoints(),
				$item->type(), DataBase::i()->escape($item->desc()), $item->id());
	
		$res = DataBase::i()->query($query);
		if ($res === false)
			return false;
	
		$item->saved();
		return true;
	}
	
	public static function byId($id)
	{
		$query = sprintf("SELECT * FROM `items` WHERE `id` = %d LIMIT 1", $id);
		$res = DataBase::i()->query($query);
		if ($res->rows() == 0)
			return null;
		return new ItemObject($res->fetch());
	}
	
	public static function byName($name)
	{
		$query = sprintf("SELECT * FROM `items` WHERE UPPER(`name`) = UPPER('%s') LIMIT 1", DataBase::i()->escape($name));
		$res = DataBase::i()->query($query);
		if ($res->rows() == 0)
			return null;
		return new ItemObject($res->fetch());
	}
	
	public static function delete($id)
	{
		if (is_object($id))
			$id = $id->id();
		$query = sprintf("DELETE FROM `items` WHERE `id` = %d LIMIT 1", $id);
		DataBase::i()->query($query);
	}
	
	public static function itemsId($from = 0, $count = null)
	{
		$query = "SELECT `id` FROM `items`";
		
		if (!is_null($count))
			$query = sprintf($query . " LIMIT %d,%d", $from, $count);
		
		$res = DataBase::i()->query($query);
		
		$items = array();
		while (($row = $res->fetch()))
			$items[] = $row["id"];
		return $items;
	}
}

?>